<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="村名字">
        <el-select
          v-model="queryParams['bankVillage.villageName']"
          placeholder="请选择村名字"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in villageList"
            :key="item.villageId"
            :label="item.villageName"
            :value="item.villageName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="villagerName">
        <el-input
          v-model="queryParams.villagerName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="villagerNumber">
        <el-input
          v-model="queryParams.villagerNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bank:villagers:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bank:villagers:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bank:villagers:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入花名册</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bank:villagers:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"  :data="villagersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="村民编号" align="center" prop="villagerId" />
      <el-table-column label="村名字" align="center" prop="bankVillage.villageName" />
      <el-table-column label="户籍号" align="center" prop="villagerDomicileNumber" />
      <el-table-column label="姓名" align="center" prop="villagerName" />
      <el-table-column label="性别" align="center" prop="villagerSex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.villagerSex"/>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="villagerAge" />
      <el-table-column label="与户主关系" align="center" prop="relationship" />
      <el-table-column label="主信贷人标志" align="center" prop="villagerMainMark">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.villagerMainMark"/>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center">
        <template slot-scope="scope">
          {{ scope.row.villagerNumber.substring(0, 6) + '********' + scope.row.villagerNumber.substring(14) }}
        </template>
      </el-table-column>


      <el-table-column label="手机号" align="center" prop="villagerPhonenumber" />
      <el-table-column label="居住地址" align="center" prop="villagerAddress" />
      <el-table-column label="信息备注" align="center" prop="villagerNotes" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bank:villagers:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bank:villagers:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改村民信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="村名字" prop="villageId">
          <el-select v-model="form.villageId" placeholder="请选择村名字" :disabled="isLimitedUser" >
            <el-option
              v-for="item in villageList"
              :key="item.villageId"
              :label="item.villageName"
              :value="item.villageId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="户籍号" prop="villagerDomicileNumber">
          <el-input v-model="form.villagerDomicileNumber" placeholder="请输入户籍号" :disabled="form.villagerId != null" />
        </el-form-item>
        <el-form-item label="姓名" prop="villagerName">
          <el-input v-model="form.villagerName" placeholder="请输入姓名" :disabled="isLimitedUser" />
        </el-form-item>
        <el-form-item label="性别" prop="villagerSex">
          <el-select v-model="form.villagerSex" placeholder="请选择性别" :disabled="isLimitedUser" >
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="主信贷人标志" prop="villagerMainMark">
          <el-select v-model="form.villagerMainMark" placeholder="请选择主信贷人标志">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="年龄" prop="villagerAge">
          <el-input v-model="form.villagerAge" placeholder="请输入年龄" :disabled="isLimitedUser" />
        </el-form-item>
        <el-form-item label="与户主关系" prop="relationship">
          <el-input v-model="form.relationship" placeholder="请输入与户主关系" :disabled="isLimitedUser" />
        </el-form-item>

        <el-form-item label="身份证号" prop="villagerNumber">
          <el-input v-model="form.villagerNumber" placeholder="请输入身份证号" :disabled="form.villagerId != null" maxlength="18" />
        </el-form-item>
        <el-form-item label="手机号" prop="villagerPhonenumber">
          <el-input v-model="form.villagerPhonenumber" placeholder="请输入手机号" maxlength="11"/>
        </el-form-item>
        <el-form-item label="居住地址" prop="villagerAddress">
          <el-input v-model="form.villagerAddress" placeholder="请输入居住地址" />
        </el-form-item>
        <el-form-item label="信息备注" prop="villagerNotes">
          <el-input v-model="form.villagerNotes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVillagers, getVillagers, delVillagers, addVillagers, updateVillagers } from "@/api/bank/villagers";
import {listVillage} from "@/api/bank/village";
import { getUserProfile } from "@/api/system/user";
import {listDomicile,addDomicile,delDomicile,getDomicileByNumber} from "@/api/bank/domicile";
import {listReview} from "@/api/bank/review";
import {listGrey} from "@/api/bank/grey";
import {getToken} from "@/utils/auth";
export default {
  name: "Villagers",
  dicts: ['sys_user_sex','sys_yes_no'],
  data() {
    return {
      //当前用户信息
      user: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isLimitedUser: true, // 默认为 true，表示受限
      // 总条数
      total: 0,
      // 村民信息管理表格数据
      villagersList: [],
      // 行政村数据
      villageList:[],
      // 弹出层标题
      title: "",
      // 是否设置了查询条件
      isQuerySet: false,
      // 是否显示弹出层
      open: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bank/villagers/importData" // todo
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        villagerName: null,
        'bankVillage.villageName':null,
        villagerNumber: null,
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        villageId:[
          { required: true, message: "村名字不能为空", trigger: "blur" }
        ],
        villagerDomicileNumber: [
          { required: true, message: "户籍号不能为空", trigger: "blur" }
        ],
        villagerName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        villagerSex: [
          { required: true, message: "性别不能为空", trigger: "blur" }
        ],
        villagerAge: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ],
        relationship: [
          { required: true, message: "与户主关系不能为空", trigger: "blur" }
        ],
        villagerNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { min: 18, max: 18, message: "身份证号必须是18位", trigger: "blur" }
        ],
        villagerPhonenumber: [
          { min: 11, max: 11, message: "手机号必须是11位", trigger: "blur" }
        ]
      }
    };
  },
  created() {

    this.getUser();
    this.getList();
  },
  methods: {
    async updatadomicile() {
      // 1. 获取村民信息列表
      const villagersResponse = await listVillagers({pageSize:100000000});
      const villagersList = villagersResponse.rows;
      console.log("sffs",villagersList);
      // 2. 获取户籍信息列表
      const domicileResponse = await listDomicile({pageSize:100000000});
      const domicileList = domicileResponse.rows;

      // 3. 获取灰名册列表
      const greyResponse = await listGrey({pageSize:10000000});
      const greyList = greyResponse.rows;

      // 4. 根据户籍号分组村民信息
      const groupedVillagers = this.groupByDomicileNumber(villagersList);

      // 5. 遍历每个户籍，对比并处理
      for (const [domicileNumber, villagers] of Object.entries(groupedVillagers)) {
        const existingDomicile = domicileList.find(d => d.domicileNumber === domicileNumber);
        if (!existingDomicile) {
          // 如果户籍信息不存在
          let domicileLabel = "0"; // 默认设置为"0"
          // 检查户籍中是否有村民在灰名册列表中
          const isInGreyList = villagers.some(villager =>
            greyList.find(grey => grey.customerNumber === villager.villagerNumber)
          );

          if (isInGreyList) {
            domicileLabel = "2"; // 如果在灰名册中，设置为"2"
          }

          // 添加户籍信息
          const domicileInfo = {
            villageId: villagers[0].villageId, // 假设村民信息中有villageId字段
            domicileNumber: domicileNumber,
            domicileLabel: domicileLabel
          };
          await addDomicile(domicileInfo);
        }
      }
    },

// 将村民信息根据户籍号分组
    groupByDomicileNumber(villagersList) {
      return villagersList.reduce((acc, villager) => {
        if (!acc[villager.villagerDomicileNumber]) {
          acc[villager.villagerDomicileNumber] = [];
        }
        acc[villager.villagerDomicileNumber].push(villager);
        return acc;
      }, {});
    },
    /** 查询当前用户信息，并筛选行政村和村民信息 */
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        // 根据用户 ID 更新 isLimitedUser，如果用户 ID 为 17 或 1，则不受限
        this.isLimitedUser = !(this.user.userId === 17 || this.user.userId === 1);
        this.getVillageList();
      });
    },

    /** 查询行政村列表，并根据当前用户ID过滤 */
    getVillageList() {
      listVillage({pageSize:1000000}).then(response => {
        // 确认response.rows是一个数组且不为空
        if (Array.isArray(response.rows) && response.rows.length) {
          // 过滤出当前用户管理的行政村，这里假设当前用户ID是user.userId
          if (this.user.userId != 17 && this.user.userId != 1) {
            this.villageList = response.rows.filter(village => village.accountManagerId == this.user.userId);
          } else {
            // 如果是特定ID，则不进行过滤，直接使用全部行政村数据
            this.villageList = response.rows;
            console.log("村民",this.villageList);
          }
        }
        // 根据过滤后的行政村ID获取村民信息
        this.getList();
      }).catch(error => {
        // 错误处理
        console.error("Error fetching village list:", error);
      });
    },

    /** 查询村民信息管理列表，并根据行政村过滤 */
    getList() {
        this.loading = true;
        // 调用获取村民信息的API，传递行政村ID和分页参数
        listVillagers(this.queryParams).then(response => {
          this.villagersList = response.rows; // 设置当前页的村民信息
          this.total = response.total; // 设置总条数，确保从后端响应中获取
          this.loading = false;
        }).catch(error => {
          console.error("获取村民信息失败:", error);
          this.loading = false;
        });


    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        villagerId: null,
        villageId: null,
        villagerDomicileNumber: null,
        villagerName: null,
        villagerSex:null,
        villagerAge:null,
        relationship: null,
        villagerMainMark:null,
        villagerPhonenumber:null,
        villagerNumber: null,
        villagerAddress: null,
        villagerNotes: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {


        this.queryParams.pageNum = 1;
        this.getList();


    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.villagerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加村民信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const villagerId = row.villagerId || this.ids
      getVillagers(villagerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改村民信息管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.villagerId != null) {
            updateVillagers(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.updatadomicile().then(() => {
                // 在户籍信息更新和插入完成后，再次获取村民列表信息
                this.getList();
              }).catch(error => {
                console.error("更新户籍信息失败:", error);
              });
            });
          } else {
            addVillagers(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.updatadomicile().then(() => {
                // 在户籍信息更新和插入完成后，再次获取村民列表信息
                this.getList();
              }).catch(error => {
                console.error("更新户籍信息失败:", error);
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      // 如果传入的是单个row，则转换为数组处理，以统一处理逻辑
      const villagerIdsToDelete = row.villagerId ? [row.villagerId] : this.ids;
      const confirmResult = await this.$modal.confirm(`是否确认删除村民信息管理编号为"${villagerIdsToDelete.join(', ')}"的数据项？`);
      if (confirmResult) {
        // 循环处理每一个要删除的村民ID
        for (const villagerId of villagerIdsToDelete) {
          await delVillagers(villagerId); // 删除村民信息

          // 重新获取当前的所有村民信息，以检查户籍号是否还被其他村民使用
          const remainingVillagers = await listVillagers({ pageSize: 100000000 });
          const villagerToDelete = this.villagersList.find(v => v.villagerId === villagerId);

          const isDomicileNeeded = remainingVillagers.rows.some(v => v.villagerDomicileNumber === villagerToDelete.villagerDomicileNumber);

          // 如果没有其他村民使用这个户籍号
          if (!isDomicileNeeded) {
            // 先通过户籍号获取domicileId
            const domicileInfo = await getDomicileByNumber(villagerToDelete.villagerDomicileNumber);
            console.log("xxx",domicileInfo);
            if (domicileInfo && domicileInfo.data.domicileId) {
              await delDomicile(domicileInfo.data.domicileId);
            }
          }
        }
        this.$modal.msgSuccess("删除成功");
        this.getList(); // 刷新列表以反映删除操作
      }
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('bank/villagers/export', {
        ...this.queryParams
      }, `villagers_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "花名册导入"; // todo
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('bank/villagers/importTemplate', {
      }, `stu_villagers_template_${new Date().getTime()}.xlsx`)  // todo
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      // 在这里调用updatadomicile方法，确保导入成功后更新和插入户籍信息
      this.updatadomicile().then(() => {
        // 在户籍信息更新和插入完成后，再次获取村民列表信息
        this.getList();
      }).catch(error => {
        console.error("更新户籍信息失败:", error);
      });
    },
// 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
